#include "radar.h"
#include "widget.h"
#include "target.h"
#include <QPainter>
#include <QRandomGenerator>

Radar::Radar (QWidget *parent)
    : QWidget(parent),wgt(qobject_cast<Widget*>(parent))
{

    setWindowTitle("Pro Radar Display");
    resize(800, 600);

    // 初始化定时器
    m_updateTimer = new QTimer(this);
    connect(m_updateTimer, &QTimer::timeout, [this](){
        m_scanAngle = (m_scanAngle + 2) % 360;
        updateTargets();
        update();
    });
    m_updateTimer->start(50); // 20 FPS

    // 初始化雷达参数
    m_center = rect().center();
    m_radius = qMin(width(), height())/2 - 50;

}

void Radar::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    // 更新中心点和半径
    m_center = rect().center();
    m_radius = qMin(width(), height())/2 - 20;

    drawBackground(painter);
    drawScanLine(painter);
    drawTargets(painter);
}

void Radar::drawBackground(QPainter &painter)
{
    // 绘制黑色背景
    // painter.fillRect(rect(), Qt::black);

    // 绘制网格
    drawGrid(painter);

    // 绘制距离刻度
    painter.setPen(Qt::green);
    for(int r = 1; r <= 5; ++r) {
        int radius = r * m_radius / 5;
        painter.drawText(m_center.x() + radius - 15, m_center.y() + 20,
                         QString::number(r*20) + "km");
    }
}

void Radar::drawGrid(QPainter &painter)
{
    painter.setPen(QPen(Qt::green, 1, Qt::DotLine));

    // 同心圆
    for(int r = 1; r <= 5; ++r) {
        painter.drawEllipse(m_center, r*m_radius/5, r*m_radius/5);
    }

    // 十字线
    painter.drawLine(m_center.x(), m_center.y() - m_radius,
                     m_center.x(), m_center.y() + m_radius);
    painter.drawLine(m_center.x() - m_radius, m_center.y(),
                     m_center.x() + m_radius, m_center.y());

    // 角度刻度
    painter.save();
    painter.translate(m_center);
    for(int angle = 0; angle < 360; angle += 30) {
        painter.save();
        painter.rotate(angle);
        painter.drawLine(0, -m_radius, 0, -m_radius + 10);
        if(angle % 90 == 0) {
            painter.drawText(20, -m_radius + 20, QString::number(angle) + "°");
        }
        painter.restore();
    }
    painter.restore();
}

void Radar::drawScanLine(QPainter &painter)
{
    QConicalGradient gradient(m_center, -m_scanAngle);
    gradient.setColorAt(0.0, QColor(0, 255, 0, 150));
    gradient.setColorAt(0.1, QColor(0, 255, 0, 50));
    gradient.setColorAt(1.0, Qt::transparent);

    painter.setBrush(gradient);
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(m_center, m_radius, m_radius);
}

void Radar::updateScanAngle(int angle) {
    scanAngle = angle;
    update();
}

void Radar::updateTargets()
{
    QMap<long, Target> map = wgt->getmap();

    for(auto it = map.begin(); it != map.end(); it++) {
        Target& target = it.value(); // 使用引用直接修改原对象

        // 记录历史位置（使用极坐标参数而非绝对坐标）
        Target historyPoint;
        historyPoint.relDistance = target.relDistance;
        historyPoint.angle = target.angle;
        historyPoint.color = target.color;
        target.history.prepend(historyPoint);
        if(it == map.begin())
        qDebug() << target.angle;
        // 更新角度（弧度制）
        it.value().angle = fmod(it.value().angle + 1, 360.0); // 直接修改map中的值
        if(target.history.size() > MAX_HISTORY) {
            target.history.removeLast();
        }
        emit updatePointData(target.id, target);  // 发出信号  如果id=-1 代表删除
    }
}

void Radar::drawTargets(QPainter &painter)
{
    painter.save();
    painter.setPen(Qt::NoPen);
    painter.translate(m_center);

    QMap<long, Target> map = wgt->getmap();

    for (auto it = map.begin(); it != map.end(); ++it) {
        const Target& target = it.value();
        QColor targetColor = target.color;

        // 计算当前目标屏幕坐标（相对圆心坐标）
        QPointF currentPos = calculatePosition(target.relDistance, target.angle);

        // 绘制历史轨迹
        for (int i = 0; i < target.history.size(); ++i) {
            const Target& historyPoint = target.history[i];
            QPointF histPos = calculatePosition(
                                                historyPoint.relDistance,
                                                historyPoint.angle);

            QColor trailColor = targetColor;
            trailColor.setAlpha(255 * (1.0 - i/float(MAX_HISTORY)));
            painter.setBrush(trailColor);
            painter.drawEllipse(histPos, 3 + i * 0.3, 3 + i * 0.3);
        }

        // 绘制当前目标
        painter.setBrush(targetColor);
        painter.drawEllipse(currentPos, 6, 6);

        // 绘制目标ID
        painter.setPen(Qt::white);
        QPointF textPos = calculatePosition(
                                            target.relDistance * 1.05,
                                            target.angle);
        painter.drawText(textPos, QString::number(target.id));
        painter.setPen(Qt::NoPen);
    }

    painter.restore();
}

// 辅助函数：根据坐标计算屏幕位置（角度单位为度）
QPointF Radar::calculatePosition(qreal relDistance, qreal angleDegrees) const
{
    // 角度转换：0度=正上方，顺时针为正方向
    qreal angleRad = qDegreesToRadians(angleDegrees); // 转换为弧度制
    return  QPointF(relDistance * m_radius * sin(angleRad),
                   -relDistance * m_radius * cos(angleRad));
}

void Radar::mousePressEvent(QMouseEvent *event)
{
    if (!wgt) return;

    QMap<long, Target> map = wgt->getmap();

    bool targetClicked = false;
    const qreal distanceThreshold = 0.1; // 10%距离容差
    const qreal angleThreshold = 10.0;    // 10度角度容差

    // 获取鼠标点击位置
    QPointF clickPos = event->pos();

    QPointF relativePos = clickPos - m_center;
    qreal clickDistance = QLineF(m_center, clickPos).length();

    // 计算点击角度（转换为0-360度，最上方为0度，顺时针增加）
    qreal clickAngle = qRadiansToDegrees(atan2(relativePos.x(), -relativePos.y()));
    clickAngle = fmod(clickAngle + 360.0, 360.0); // 确保在0-360范围内
    clickPos.setX(clickPos.x() - width() / 2);
    clickPos.setY(clickPos.y() - height() / 2);
    qDebug() << QString("点击检测 - 距离: %1/%2, 角度: %3° x:%4, y:%5")
                    .arg(clickDistance, 0, 'f', 1)
                    .arg(m_radius)
                    .arg(clickAngle, 0, 'f', 1)
                    .arg(clickPos.x())
                    .arg(clickPos.y());

    // 检查每个目标
    for (auto& target : map) {
        // 计算角度差
        qreal angleDiff = fabs(clickAngle - target.angle);

        // 计算距离差
        qreal distanceDiff = qAbs(target.relDistance - clickDistance / m_radius);

        // 调试输出
        qDebug() << QString("目标%1 - 距离差: %2%, 角度差: %3°")
                        .arg(target.id)
                        .arg(distanceDiff*100, 0, 'f', 1)
                        .arg(angleDiff, 0, 'f', 1);

        // 扇形区域检测
        if (distanceDiff <= distanceThreshold && angleDiff <= angleThreshold) {
            QString info = QString("目标%1 | 距离: %2km | 速度: %3km/h | 方位: %4°")
                               .arg(target.id)
                               .arg(clickDistance / m_radius * 100, 0, 'f', 1)
                               .arg(target.speed, 0, 'f', 1)
                               .arg(wgt->convertDirection(target.angle));

            wgt->setImLabelText(info);
            id = target.id;
            targetClicked = true;
            break;
        }
    }

    // 未命中任何目标
    if (!targetClicked) {
        wgt->setImLabelText(QString("未选中目标 | 点击位置: 方位%1° 距离%2km")
                                .arg(clickAngle, 0, 'f', 1)
                                .arg(clickDistance / m_radius * 100, 0, 'f', 1));
    }

    QWidget::mousePressEvent(event);
}

// void Radar::resizeEvent(QResizeEvent *event)
// {
//     Radar::resizeEvent(event);
//     // 只需要更新中心点和半径，目标位置会自动适应
//     m_center = rect().center();
//     m_radius = qMin(width(), height())/2 - 50;
//     update();
// }
